<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="common/include :: header('结算单明细列表')" />
</head>
<body>
<div class="ui-layout-center">

    <div class="col-sm-12 search-collapse">
        <div class="col-sm-12" >
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">客户姓名：</label>
                    <label class="col-sm-6 control-label">[[${statement.customerName}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">联系方式：</label>
                    <label class="col-sm-6 control-label">[[${statement.customerPhone}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12" >
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">车牌编号牌：</label>
                    <label class="col-sm-6 control-label">[[${statement.licensePlate}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">汽车类型：</label>
                    <label class="col-sm-6 control-label">[[${statement.carSeries}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12" >
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">服务类型：</label>
                    <label class="col-sm-6 control-label">[[${@dict.getLabel('si_service_catalog',statement.serviceType)}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">到店时间：</label>
                    <label class="col-sm-6 control-label" th:text="${#dates.format(statement.actualArrivalTime, 'yyyy-MM-dd HH:mm')}"></label>
                </div>
            </div>
        </div>
        <div class="col-sm-12" >
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">总消费金额：</label>
                    <label class="col-sm-6 control-label" id="totalAmount">[[${statement.totalAmount}]]</label>
                </div>
            </div>
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">实付价格：</label>
                    <label class="col-sm-6 control-label" id="actuallyPaid">[[${statement.totalAmount-statement.discountAmount}]]</label>
                </div>
            </div>
        </div>
        <div class="col-sm-12" >
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-6 control-label">优惠价格：</label>
                    <input class="col-sm-6" id="discountAmount" type="number" onchange="discountFun()" name="discountAmount" th:field="${statement.discountAmount}"/>
                </div>
            </div>
        </div>
    </div>
    <div class="btn-group-sm" id="myTool" role="group">
        <a class="btn btn-success" onclick="saveFun()" shiro:hasPermission="business:serviceItem:add">
            <i class="fa fa-plus"></i> 保存
        </a>
        <a id="payBtn" class="btn btn-info" onclick="payFun()" shiro:hasPermission="business:statementItem:payStatement">
            <i class="fa fa-cc-visa"></i> 确认支付
        </a>
    </div>
    <div class="col-sm-12 select-table table-striped">
        <table id="statementTable"></table>
    </div>
</div>


<div class="ui-layout-east">
    <div class="container-div">
        <div class="row">
            <!--模块一,用于数据的高级查询-->
            <div class="col-sm-12 search-collapse">
                <form id="serviceItem-form">
                    <div class="select-list">
                        <ul>
                            <li>
                                服务名称：<input type="text" name="name"/>
                            </li>
                            <li>
                                是否套餐：
                                <select name="carPackageStatus" th:with="type=${@dict.getType('si_car_package')}">
                                    <option value="">所有</option>
                                    <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                                </select>
                            </li>
                            <li>
                                服务分类：
                                <select name="serviceCatalogStatus" th:with="type=${@dict.getType('si_service_catalog')}">
                                    <option value="">所有</option>
                                    <option th:each="dict : ${type}" th:text="${dict.label}" th:value="${dict.value}"></option>
                                </select>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>
            <!--表格模块,使用了异步刷新的前端框架bootstrap-table-->
            <div class="col-sm-12 select-table table-striped">
                <table id="serviceTable"></table>
            </div>
        </div>
    </div>
</div>

<th:block th:include="common/include :: footer" />
<th:block th:include="common/include :: layout-latest"/>

<script>
    $('body').layout({
        east__size:	'35%',
    });
    $(function() {
        var prefix = ctx + "/business/statementItem";
        var statementId = [[${statement.id}]];
        var options = {
            uniqueId:"itemId",
            toolbar : "myTool",
            //请求是带参数过去只查询上架的产品
            id: "statementTable",
            url: prefix + "/query?statementId=" + statementId,						//查询的url路径
            columns: [
                {
                    field: 'id',
                    title: '结算单id',
                    visible: false						//设为false表示隐藏id列,在页面上不做显示
                },
                //添加服务单项的id,因为每一个服务单的id是唯一的
                {
                    field: 'itemId',
                    title: '服务单项的id',
                    visible: false						//设为false表示隐藏id列,在页面上不做显示
                },
                {
                    field: 'itemName',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'itemPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'itemQuantity',
                    title: '购买数量',
                    sortable: true,
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        //给左侧的加号添加事件,但是他的id要是itemId也就是中间表中服务单项的id
                        var actions = [];
                        actions.push('<a class="btn btn-primary btn-plus " href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.itemId + '\')"><i class="fa fa-remove fa-plus"></i></a>');
                        actions.push('<a class="btn btn-danger btn-plus" href="javascript:void(0)"' +
                            ' onclick="decrItem(\'' + row.itemId + '\')"><i class="fa fa-remove fa-minus"></i></a>');

                        return actions.join(' ');
                    }
                }]
        };
        $.table.init(options);
    });

    $(function() {
        var prefix = ctx + "/business/serviceItem";
        var options = {
            uniqueId : "id",
            id:"serviceTable",
            //请求是带参数过去只查询上架的产品
            url: prefix + "/query?saleStatus=1",						//查询的url路径
            columns: [
                {
                    field: 'id',
                    title: '服务项id',
                    visible: false						//设为false表示隐藏id列,在页面上不做显示
                },
                {
                    field: 'name',
                    title: '服务项名称',
                    sortable: true
                },
                {
                    field: 'originalPrice',
                    title: '服务项价格',
                    sortable: true
                },
                {
                    field: 'info',
                    title: '备注信息',
                    sortable: true,
                    formatter: function(value, row, index) {
                        return $.table.tooltip(value, 0, "open");
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-primary btn-plus " href="javascript:void(0)"' +
                            ' onclick="addItem(\'' + row.id + '\')"><i class="fa fa-remove fa-plus"></i></a>');
                        return actions.join(' ');
                    }
                }]
        };
        $.table.init(options);
    });

    //点击加号往左边表中添加数据
    function addItem(id) {
        //通过id获取到被点击的那一条数据
        var rs = $('#serviceTable').bootstrapTable('getRowByUniqueId',id);
        //通过bootstrapTable的append的属性,把数据添加到另外一个表格当中
        var newData = [{itemId:rs.id , itemName:rs.name , itemPrice:rs.originalPrice ,itemQuantity:1}];
        var statementData = $('#statementTable').bootstrapTable("getRowByUniqueId",id);
        if (statementData) {
            //更新单元格中的数据
            $('#statementTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field: 'itemQuantity',
                value: statementData.itemQuantity + 1
            });
        } else {
            $('#statementTable').bootstrapTable('append',newData);
        }
        discountFun();
    }

    //点击减号减数据
    function decrItem(id) {
        //根据单项的id
        var statementData = $('#statementTable').bootstrapTable('getRowByUniqueId',id);
        if (statementData.itemQuantity > 1) {
            //更新单元格中的数据
            $('#statementTable').bootstrapTable('updateCellByUniqueId', {
                id: id,
                field: 'itemQuantity',
                value: statementData.itemQuantity - 1
            });
        } else {
            $('#statementTable').bootstrapTable('removeByUniqueId',id);
        }
        discountFun();
    }
    //同步修改金额
    function discountFun(){
        //拿到左侧表格中所有的数据
        var data= $('#statementTable').bootstrapTable('getData',false);

        //定义一个变量用于接收总金额
        var totalAmount = 0;
        //通过遍历计算出总金额
        $.each(data, function(index , item){
            totalAmount += item.itemPrice * item.itemQuantity;
        });
        //拿到优惠金额
        var discountAmount = $('#discountAmount').val();
        //给总金额进行赋值
        $('#totalAmount').html(totalAmount);
        //如果集合中没有元素,那么就把所有的金额设置为0
        if (data == null) {
            //优惠金额
            $('#discountAmount').val(0);
            //总金额
            $('#totalAmount').html(0);
            //实付金额
            $('#actuallyPaid').html(0);
        }
        //如果优惠金额小于0就把优惠金额设置为0
        if (discountAmount < 0 ) {
            $('#discountAmount').val(0);
            return
        }
        //如果优惠金额大于总金额,那么就把优惠金额设置为0
        if (discountAmount > totalAmount ) {
            $('#discountAmount').val(0);
            return
        }
        //获取实付金额的值
        var realPrice = totalAmount - discountAmount;
        //给实付金额进行赋值
        $('#actuallyPaid').html(realPrice);
    }

    //保存服务项导数据库
    function saveFun() {
        //获取model中的结算单id => statementId
        var statementId = [[${statement.id}]];
        //获取表中的所有数据
        var data= $('#statementTable').bootstrapTable('getData',false);
        //通过遍历把statementId赋值给表中的
        $.each(data,function(index , item){
            item.statementId = statementId;
        });
        console.log(data);
        //在data集合的最后一个元素,添加优惠金额,和结算单的id
        data.push({"itemPrice":$('#discountAmount').val() , "statementId" : statementId});

        //发送ajax请求
        var config = {
            url:"/business/statementItem/saveItems",
            type: 'post',
            dataType: 'json',
            contentType:"application/json",
            //请求JSON格式的数据到后端
            data: JSON.stringify(data),
            beforeSend: function () {
                $.modal.loading("正在处理中，请稍后...");
            },
            success: function(result) {
                //点击保存时刷新页面,防止data.push({"itemPrice":$('#discountAmount').val() , "statementId" : statementId});
                //这条数据显示出来
                //本来底层是有刷新功能的,但是由于页面上多张表,所以若依底层的刷新功能没有效果,我们要指定表的id进行刷新
                $.table.refresh("statementTable");
                $.operate.ajaxSuccess(result);
            }
        };
        $.ajax(config)
    }

    //确认支付
    function payFun() {
        //获取服务单的id
        var statementId = [[${statement.id}]];
        //弹出模态框
        $.modal.confirm("确定要支付吗?" , function() {
            //发送ajax请求,带上服务单的id到后端
            $.operate.get("/business/statementItem/pay?statementId=" + statementId);
        })
    }
</script>
</body>
</html>